<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of NewsService
 *
 * @author Administrator
 */
vendor('simplehtmldom.simple_html_dom');
import('@.Service.UrlsService');

class NewsService {

    /**
     * 首页上的显示最新新闻
     * @param type $module
     * @param type $limit
     * @return type 
     */
    function listLatestNews($module, $limit) {
        $newsTable = D('message');
        $where['module'] = array('eq', $module);
        $result = $newsTable->where($where)->order('datetime desc')->limit($limit)->select();
//        dump($newsTable->getLastSql());

        return $result;
    }

    function create() {
        return D('message')->create();
    }

    function delete($id) {
        D('message')->data(array('id' => $id))->delete();
    }

    function update($message) {
        D('message')->save($message);

//        echo(D('message')->getLastSql());
    }

    function listMessagesByOrderMessage($message) {
        $newsTable = D('message');
        $where['datetime'] = array('lt', $message['datetime']);
        return $newsTable->where($where)->limit(4)->select();
    }

    function fastNavigation($message) {
        $newsTable = D('message');

        $prev = $newsTable->where("datetime < '" . $message['datetime'] . "'")->order('datetime desc')->limit(1)->find();
        $next = $newsTable->where("datetime > '" . $message['datetime'] . "'")->order('datetime asc')->limit(1)->find();


        return array('prev' => $prev, 'next' => $next);
    }

    function countMessages() {
        $newsTable = D('message');
        //$where['module'] = array('eq', $module);

        return $newsTable->count();
    }

    function listMessages($offset, $limit, $order, $field='*') {
        $newsTable = D('message');
        //$where['module'] = array('eq', $module);
        return $newsTable->field($field)->order($order)->limit($offset . ',' . $limit)->select();
    }

    function findMessageById($id) {
        return D('message')->find($id);
    }

    function writeUrl($url, $module) {
        $html = file_get_html($url);

        $page = $html->getElementById('all_page');

        $lis = $page->parent()->find('ul li');

        $urls = array();
        $urlsService = new UrlsService();
//        $index = 0;
        foreach ($lis as $li) {
            $a = $li->first_child();
            //未拉取进行保存
            if ($urlsService->isHas($this->joinLink($module, $a->attr['href']), 'news')) {
                $img = $a->first_child();
                array_push($urls, array('url' => $this->joinLink($module, $a->attr['href']),
                    'url_icon' => $img->attr['src'],
                    'load' => 0,
                    'load_over' => 0,
                    'datetime' => date('Y-m-d H:m:s'),
                    'type' => 'news'));
//                $urlsService->insert(array('url' => $this->joinLink($module, $a->attr['href']),
//                    'url_icon' => $img->attr['src'],
//                    'load' => 0,
//                    'load_over' => 0,
//                    'datetime' => date('Y-m-d H:m:s'),
//                    'type' => 'news'));
//                $index++;
            }
        }

        $html->clear();

//        $urls = array_unique($urls);
        $urlsService->insertAll($urls);
        return count($urls);
//        return $index;
    }

    private function joinLink($module, $url) {
        if ('new' == $module) {
            return 'http://news.cnmo.com' . $url;
        } elseif ('price' == $module) {
            return 'http://price.cnmo.com' . $url;
        }
        return 'http://reviews.cnmo.com' . $url;
    }

    function releaseNews() {
        $urlsService = new UrlsService();
        $url = $urlsService->findReleaseByType('news');

        //全部发布完毕
        if (empty($url)) {
            return false;
        }

        $new = $this->getNewsContent($url);
        //有可能未能抓取
        if (!is_bool($new)) {
            $this->insert($new);
        }

        $urlsService->updateUrls($url['id']);

        return true;
    }

    function insert($new) {
        $newTable = D('message');
        $newTable->startTrans();
        $lastId = $newTable->add($new);
        $newTable->commit();

        return $lastId;
    }

    private function gb2312ToUtf8($str) {
        return iconv('gb2312', 'utf-8', $str);
    }

    function getNewsContent($url) {
        $html = file_get_html($url['url']);
        if (is_bool($html)) {
            return false;
        }

        $contentDiv = array_shift(array_shift($html->find('body'))->find('div.wrapper > div.wrap_l > div.linetb2'));

        if (ereg('^http://news', $url['url'])) {
            $new['module'] = '苹果新闻';
        } elseif (ereg('^http://price', $url['url'])) {
            $new['module'] = '苹果行情';
        } else {
            $new['module'] = '苹果评测';
        }
        $new['icon'] = $url['url_icon'];
        $new['name'] = $this->gb2312ToUtf8($contentDiv->children(0)->children(0)->text());

        $info = split(' ', $contentDiv->children(1)->text());
        $new['datetime'] = $this->gb2312ToUtf8($info[count($info) - 1]);

        //删除  踩 顶
        $removeElement = $contentDiv->children(4)->last_child();

        $contentTextElement = $contentDiv->children(4)->find('p');

        $text = '';
        foreach ($contentTextElement as $p) {
            $text .= '<p>' . $p->innertext() . '</p>';
        }
        $new['content_text'] = $this->gb2312ToUtf8($text);

        $p = array_shift($contentDiv->children(4)->find('p'));
        $new['content'] = $this->gb2312ToUtf8($p->text());

        $new['author'] = '白泡泡';
//        dump($new);
//        return;

        $html->clear();
        return $new;
    }

}

?>
